package tech.wetech.admin3.controller;

import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.model.AooPersCertiData;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.service.AooPersCertiDataService;
import tech.wetech.admin3.sys.service.AooPhoneCodeService;
import tech.wetech.admin3.sys.service.AooUserService;
import tech.wetech.admin3.sys.service.OssService;
import tech.wetech.admin3.util.CustomResponse;
import tech.wetech.admin3.util.GetDateUtil;
import tech.wetech.admin3.util.LianduAPIUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class AooPersCertiDataController {
  private final OssService ossService;
  private final AooUserService aooUserService;
  private final AooPersCertiDataService aooPersCertiDataService;
  private AooPhoneCodeService phoneCodeService;

  @Value("${liandu.api.personalVeriApi}")
  private String personalVeriApi;
  @Value("${liandu3ele}")
  private boolean liandu3ele;

  @Autowired
  private LianduAPIUtils lianduAPIUtil;

  public AooPersCertiDataController(
    OssService ossService,
    AooUserService aooUserService,
    AooPersCertiDataService aooPersCertiDataService,
    AooPhoneCodeService phoneCodeService
  ) {
    this.ossService = ossService;
    this.aooUserService = aooUserService;
    this.aooPersCertiDataService = aooPersCertiDataService;
    this.phoneCodeService = phoneCodeService;
  }

  @Transactional
  @PostMapping("auth-personal")
  public ResponseEntity<?> authPersonal(
    @RequestParam("email") String email,
    @RequestParam("idName") String idName,
    @RequestParam("idNo") String idNo,
    @RequestParam("mobile") String mobile,
    @RequestParam("vericode") String vericode,
    @RequestParam(value = "company", required = false) String company,
    @RequestParam(value = "job", required = false) String job,
    @RequestParam(value = "education", required = false) String education,
    @RequestParam(value = "college", required = false) String college,
    @RequestParam(value = "property", required = false) String property,
    @RequestParam("idCardPhotoPros") MultipartFile idCardPhotoPros,
    @RequestParam("idCardPhotoCons") MultipartFile idCardPhotoCons
  ) {
    boolean flag = phoneCodeService.verifyCode(mobile, vericode);
    if (!flag) {
      return ResponseEntity.ok(new CustomResponse.r1("验证码错误或已过期", false, ""));
    }
    AooPersCertiData aooPersCertiData = new AooPersCertiData();
    aooPersCertiData.setEmail(email);

    aooPersCertiData.setIdName(idName);
    aooPersCertiData.setIdNo(idNo);
    aooPersCertiData.setMobile(mobile);
    aooPersCertiData.setCompany(company);
    aooPersCertiData.setJob(job);
    aooPersCertiData.setEducation(education);
    aooPersCertiData.setCollege(college);
    aooPersCertiData.setProperty(property);
    aooPersCertiData.setCreateDate(GetDateUtil.getYyyyMMddHHmmss());

    if (!idCardPhotoPros.isEmpty()) {
      String idCardPhotoProsUrl = ossService.uploadImage(idCardPhotoPros);
      aooPersCertiData.setIdCardPhotoProsUrl(idCardPhotoProsUrl);
    }
    if (!idCardPhotoCons.isEmpty()) {
      String idCardPhotoConsUrl = ossService.uploadImage(idCardPhotoCons);
      aooPersCertiData.setIdCardPhotoConsUrl(idCardPhotoConsUrl);
    }

    // 个人三要素检验
    JSONObject responseJson = lianduAPIUtil.personalThreeElementCheck(personalVeriApi, idNo, idName, mobile).join();
    System.out.println("response-----" + responseJson);

    String status = responseJson.getStr("status");
    boolean result = "ok".equals(status);

    if (!liandu3ele || result) { // 三要素通过执行
      AooUser user = aooUserService.findByEmail(email);
      if (user == null) {
        return ResponseEntity.ok(new CustomResponse.r1<>("认证邮箱和用户不匹配", false, null));
      }

      AooPersCertiData savedData = aooPersCertiDataService.upload(aooPersCertiData);
      if (savedData != null && savedData.getId() != null) { // 假设savedData有一个ID字段来确认持久化
        boolean res = aooPersCertiDataService.resetStatus(email, 2, null);  // status：2，个人认证不审核，直接通过
        if (!res) {
          return ResponseEntity.ok(new CustomResponse.r1<>("认证邮箱和用户不匹配", false, null));
        }

        user.setVerifiedPhone(mobile);
        return ResponseEntity.ok(new CustomResponse.r1<>("提交成功", true, savedData));
      } else {
        // 保存失败的情况
        return ResponseEntity.ok(new CustomResponse.r1<>("个人三要素验证通过，提交失败，请重新提交", false, null));
      }
    } else {
      return ResponseEntity.ok(new CustomResponse.r1<>(responseJson.getStr("message"), false, responseJson));
    }
  }

  @GetMapping("/getall/pers")
  public ResponseEntity<?> getAllData(
    @RequestParam("page") int page,
    @RequestParam("size") int size
  ) {
    List<?> data = aooPersCertiDataService.getAllData();
    int total = data.size();
    int start = page * size;
    int end = Math.min(start + size, data.size());

    List<?> paginatedList;

    if (start < total) {
      paginatedList = data.subList(start, end);
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);

    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, result));
  }

}
